<?php
namespace App\Util;

use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class FileHelper {
    /**
     * 验证文件
     * @author gaoyoulong
     * @param $file
     * @param $allowType
     * @param $allowSize
     * @return Result
     */
    public static function valid($file,$allowType=null,$allowSize=null){
        if($file->getError() !== UPLOAD_ERR_OK){
            return Result::failure($file->getErrorMessage());
        }

        //检查文件是否有效
        if (!$file->isValid()) {
            return Result::failure('文件失效');
        }

        $extension = $file->getClientOriginalExtension();
        if(empty($allowType)){
            $allowType = ['jpg','jpeg','gif','png'];
        }

        if(!in_array($extension,$allowType)){
            return Result::failure('格式不对');
        }

        $size = $file->getClientSize();
        if(empty($allowSize)){
            $allowSize = 5*1024*1024;
        }
        if($size > $allowSize){
            return Result::failure('上传文件大于设定限制');
        }

        return Result::success();
    }

    /**
     * 上传文件到本地
     * @author gaoyoulong
     * @param $file
     * @param $prefix 上传文件路径前缀
     * @param $driver 驱动
     * @return Result
     */
    public static function toLocal($file,$prefix,$driver='local'){
        $contents = file_get_contents($file->getPath().DIRECTORY_SEPARATOR.$file->getFilename());
        $fileName = time().'_'.substr(md5($file->getClientOriginalName()),0,10).'.'.$file->getClientOriginalExtension();
        $filePath = $prefix.DIRECTORY_SEPARATOR.$fileName;
        $res = Storage::disk($driver)->put($filePath,$contents);
        if($res !== false){
            return Result::success('上传成功！')->setData($fileName);
        }
        else{
            return Result::failure('上传失败，请重新尝试！');
        }
    }

    public static function rename($filename) {
        if(!$filename){
            return Result::failure('缺少文件');
        }

        //转移到正式路径，删除临时路径
        $tempFile = config('filesystems.disks.apk.root').DIRECTORY_SEPARATOR.config('image.tempPicPath').DIRECTORY_SEPARATOR.$filename;
        $formalFile = config('filesystems.disks.apk.root').DIRECTORY_SEPARATOR.config('image.originalPicPath').DIRECTORY_SEPARATOR.$filename;
        //判断路径
        $dir = dirname($formalFile);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        if(file_exists($tempFile)){
            copy($tempFile,$formalFile); //拷贝到新目录
            unlink($tempFile);
        }

        return Result::success();
    }
}